<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Member Group model
 * model สำหรับ group management
 * @package Member
 * @subpackage Model
 * @category Group
 */
class Group_m extends MY_Model {

    function __construct() {

        parent::__construct();
    }
    private $group_table = 'mem_group';
    private $system_table = 'mem_system';
    /**
     * Get All Group and id
     * เรียก Group ทั้งหมด
     * @return array ['value'] = 'group name';
     */
    function getAllGroup(){
        $res = $this->db->get($this->group_table);
        foreach($res->result() as $row){
            $data[$row->value] = $row->group_name;
        }

        return $data;
    }
    /**
     * get group and sort
     * @param string เรียงตามอะไร id,value,group_name
     */
    function getGroupSort($order){
        $this->db->order_by($order,'desc');
        $res = $this->db->get($this->group_table);
        return $res;
    }

        /*
     * Add new group
     * $param array group_name,value
     */
    function addGroup($array){
        $this->db->insert($this->group_table,$array);
//        echo $this->db->last_query();
    }

    /**
     * Delete group
     * Move all user to member group and delete this group
     * @uses getPermissionFromId()
     */
    function deleteGroup($id){
        //get memgroup from this id
        $group = $this->getPermissionFromId($id);
        if($group){
            $this->db->set('memgroup',60);
            $this->db->where('memgroup',$group->value,false);
            $this->db->update($this->system_table);
//            echo $this->db->last_query();
            
            $this->db->where('id',$id);
            $this->db->delete($this->group_table);
//            echo $this->db->last_query();
//            die();
        }
    }

    function updateGroupUser($array){
        if($array['id']=='1')die(); //not change admin
        $this->db->set('memgroup',$array['memgroup']);
        $this->db->where('id',$array['id']);
        $this->db->update($this->system_table);
    }

    /**
     * Get Permission from group id
     * @param int group id
     * @return array ['value']
     */
    function getPermissionFromId($id){
        $this->db->select('value');
        $this->db->where('id',$id,'false');
        $res = $this->db->get($this->group_table);
        
        if($res->num_rows() ==1){
            return $res->row();
        }
        return null;
    }
    /**
     * get group name from group value
     * @param int group value
     * @return array ['group_name']
     */
    function getGroupNameFromValue($value){
        $this->db->select('group_name');
        $this->db->where('value',$value);
        $res = $this->db->get($this->group_table);
        if($res->num_rows() ==1){
            return $res->row();
        }
        return null;
    }

}
